package com.genexususa.eo.bing.data.requests;

import com.genexususa.eo.bing.CampaignManagementServiceClasses.Keyword;
import com.genexususa.eo.bing.data.GxItemException;
import com.genexususa.eo.bing.data.wsSubclasses.GxKeyword;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GxKeywordsAdGroupRequest {
    private long gxAdGroupId;
    private long bingAdGroupId;
    private Keyword[] keywords;

    public GxKeywordsAdGroupRequest(Element element) throws IllegalArgumentException, GxItemException {
        if (element.getElementsByTagName("GxAdGroupId").getLength() > 0 &&
            element.getElementsByTagName("GxAdGroupId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("GxAdGroupId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.gxAdGroupId = Long.valueOf(((Node)element.getElementsByTagName("GxAdGroupId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing external AdGroup id");
        }
        if (element.getElementsByTagName("BingAdGroupId").getLength() > 0 &&
            element.getElementsByTagName("BingAdGroupId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("BingAdGroupId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.bingAdGroupId = Long.valueOf(((Node) element.getElementsByTagName("BingAdGroupId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing Bing AdGroup id");
        }
        NodeList keywordsNode = element.getElementsByTagName("KeywordCollection");
        if (keywordsNode.getLength() > 0) {
            NodeList keywordNode = ((Element)keywordsNode.item(0)).getElementsByTagName("Keyword");
            this.keywords = new Keyword[keywordNode.getLength()];
            for (int i=0; i<keywordNode.getLength(); i++) {
                keywords[i] = new GxKeyword((Element)keywordNode.item(i));
            }
        } else {
            throw new GxItemException("No Keywords were found for AdGroup " + this.gxAdGroupId);
        }
    }

    public long getGxAdGroupId() {
        return gxAdGroupId;
    }

    public long getBingAdGroupId() {
        return bingAdGroupId;
    }

    public Keyword[] getKeywords() {
        return keywords;
    }
}
